<?php

// +----------------------------------------------------------------------
// | Copyright (c) 2016－03－21 http://www.cencn.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 林群伟  <56583965@qq.com> <http://www.xzqly.com>
// +----------------------------------------------------------------------

namespace Common\Model;

use Think\Model;

/**
 * 菜单模型
 * @author 林群伟
 */
class AuthGroupModel extends Model {

    const MEMBER = 'member';
    const UCENTER_MEMBER = 'ucenter_member';
    const AUTH_GROUP_ACCESS = 'auth_group_access'; // 关系表表名
    const AUTH_EXTEND = 'auth_extend';       // 动态权限扩展信息表
    const AUTH_GROUP = 'auth_group';        // 用户组表名

    protected $_validate = array(
        array('title', 'require', '必须设置用户组标题', Model::MUST_VALIDATE, 'regex', Model::MODEL_INSERT),
        //array('title','require', '必须设置用户组标题', Model::EXISTS_VALIDATE  ,'regex',Model::MODEL_INSERT),
        array('description', '0,80', '描述最多80字符', Model::VALUE_VALIDATE, 'length', Model::MODEL_BOTH),
            // array('rules','/^(\d,?)+(?<!,)$/', '规则数据不合法', Model::VALUE_VALIDATE , 'regex'  ,Model::MODEL_BOTH ),
    );

    public function getAuthGroupList($map, $field, $order) {
        return $this->field($field)->where($map)->order($order)->select();
    }

    /**
     * 返回用户组列表
     * 默认返回正常状态的管理员用户组列表
     * @param array $where   查询条件,供where()方法使用
     *
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function getGroups($where = array()) {
        $map = array('status' => 1);
        $map = array_merge($map, $where);
        return $this->where($map)->select();
    }

    /**
     * 返回用户所属用户组信息
     * @param  int    $uid 用户id
     * @return array  用户所属的用户组 array(
     *                                         array('uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
     *                                         ...)
     */
    public function getUserGroup($uid) {
        static $groups = array();
        if (isset($groups[$uid]))
            return $groups[$uid];
        $prefix = C('DB_PREFIX');
        $user_groups = M()
                ->field('uid,group_id,title,description,rules')
                ->table($prefix . self::AUTH_GROUP_ACCESS . ' a')
                ->join($prefix . self::AUTH_GROUP . " g on a.group_id=g.id")
                ->where("a.uid='$uid' and g.status='1'")
                ->select();
        $groups[$uid] = $user_groups ? $user_groups : array();
        return $groups[$uid];
    }

    /**
     * 获取列表 name－>id
     */
    public function getAuthGroupFiled($map, $field = '*') {
        return $this->where($map)->getField($field);
    }
    /**
     * 检查id是否全部存在
     * @param array|string $gid  用户组id列表
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function checkId($modelname,$mid,$msg = '以下id不存在:'){
        if(is_array($mid)){
            $count = count($mid);
            $ids   = implode(',',$mid);
        }else{
            $mid   = explode(',',$mid);
            $count = count($mid);
            $ids   = $mid;
        }

        $s = M($modelname)->where(array('id'=>array('IN',$ids)))->getField('id',true);
        if(count($s)===$count){
            return true;
        }else{
            $diff = implode(',',array_diff($mid,$s));
            $this->error = $msg.$diff;
            return false;
        }
    }

    /**
     * 检查用户组是否全部存在
     * @param array|string $gid  用户组id列表
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function checkGroupId($gid){
        return $this->checkId('AuthGroup',$gid, '以下用户组id不存在:');
    }
    
        /**
     * 把用户添加到用户组,支持批量添加用户到用户组
     * @author 朱亚杰 <zhuyajie@topthink.net>
     *
     * 示例: 把uid=1的用户添加到group_id为1,2的组 `AuthGroupModel->addToGroup(1,'1,2');`
     */
    public function addToGroup($uid,$gid){
        $uid = is_array($uid)?implode(',',$uid):trim($uid,',');
        $gid = is_array($gid)?$gid:explode( ',',trim($gid,',') );

        $Access = M(self::AUTH_GROUP_ACCESS);
        if( isset($_REQUEST['batch']) ){
            //为单个用户批量添加用户组时,先删除旧数据
            $del = $Access->where( array('uid'=>array('in',$uid)) )->delete();
        }

        $uid_arr = explode(',',$uid);
		$uid_arr = array_diff($uid_arr,array(C('USER_ADMINISTRATOR')));
        $add = array();
        if( $del!==false ){
            foreach ($uid_arr as $u){
            	//判断用户id是否合法
            	if(M('Member')->getFieldByUid($u,'uid') == false){
            		$this->error = "编号为{$u}的用户不存在！";
            		return false;
            	}
                foreach ($gid as $g){
                    if( is_numeric($u) && is_numeric($g) ){
                        $add[] = array('group_id'=>$g,'uid'=>$u);
                    }
                }
            }
            $Access->addAll($add);
        }
        if ($Access->getDbError()) {
            if( count($uid_arr)==1 && count($gid)==1 ){
                //单个添加时定制错误提示
                $this->error = "不能重复添加";
            }
            return false;
        }else{
            return true;
        }
    }
}
